﻿using NPOI.OpenXmlFormats.Dml;
using NPOI.OpenXmlFormats.Dml.WordProcessing;
using NPOI.OpenXmlFormats.Wordprocessing;
using NPOI.XWPF.UserModel;
using System;
using System.IO;
using System.Threading.Tasks;
using System.Web;
using System.Xml;
using Microsoft.Extensions.Configuration;

namespace MDT.LifeSewagePlatform.Conmmon
{
    public class MangerWord : IManagerWord
    {
        private readonly IConfiguration _config;
        public MangerWord(IConfiguration config)
        {
            _config = config;
        }
        private XWPFDocument doc { get; set; }
        private int PicIndex { get; set; }
        public int GetPicIndex()
        {
            return PicIndex;
        }
        public async Task CreateDocAsync()
        {
            await Task.Run(async () =>
            {
                if (doc == null)
                {
                    doc = new XWPFDocument();
                    PicIndex = 1;
                    await SetStylesDoc();
                }
            });

        }

        /// <summary>
        /// 针对一行文字
        /// </summary>
        /// <param name="str"></param>
        public async Task CreatePAsync(string str)
        {
            await Task.Run(() =>
            {
                XWPFParagraph p = doc.CreateParagraph();
                p.Alignment = ParagraphAlignment.CENTER;
                XWPFRun run = p.CreateRun();
                run.IsBold = false;
                run.SetText(str);
                run.FontSize = 24;
                run.SetFontFamily("华文中宋", FontCharRange.None);//设置雅黑字体
            });

        }

        public async Task CreatePAsync(string str, Action<XWPFParagraph, XWPFRun> act = null)
        {
            await Task.Run(() =>
             {
                 XWPFParagraph p = doc.CreateParagraph();
                 XWPFRun run = p.CreateRun();

                 if (act != null)
                 {
                     act.Invoke(p, run);
                 }
                 else
                 {
                     run.IsBold = true;
                     run.FontSize = 24;
                 }
                 run.SetText(str);
                 run.SetFontFamily("华文中宋", FontCharRange.None);//设置雅黑字体
             });

        }
        public void OneTitle(XWPFParagraph p, XWPFRun run)
        {
            run.FontSize = 16;
            run.IsBold = true;
            p.Style = "1";
            run.FontFamily = "黑体";
        }

        public void TwoTitle(XWPFParagraph p, XWPFRun run)
        {
            run.FontSize = 14;
            run.IsBold = true;
            p.Style = "2";
            run.FontFamily = "宋体";
        }

        public void Content(XWPFParagraph p, XWPFRun run)
        {
            run.FontSize = 14;
            run.IsBold = false;
            run.FontFamily = "宋体";
            run.AddTab();
        }

        public async Task CreatePAsync(Action<XWPFParagraph, XWPFRun> act = null)
        {
            await Task.Run(() =>
            {
                XWPFParagraph p = doc.CreateParagraph();
                XWPFRun run = p.CreateRun();

                if (act != null)
                {
                    act.Invoke(p, run);
                }
                else
                {
                    run.IsBold = true;
                    run.FontSize = 24;
                }
                run.SetFontFamily("华文中宋", FontCharRange.None);//设置雅黑字体
            });

        }
        public async Task CreatePAsync(string[] str, Action<string[], XWPFParagraph, XWPFRun> act = null)
        {
            await Task.Run(() =>
            {
                XWPFParagraph p1 = doc.CreateParagraph();
                p1.Alignment = ParagraphAlignment.CENTER;

                XWPFRun runTitle = p1.CreateRun();
                runTitle.IsBold = true;
                runTitle.FontSize = 16;
                runTitle.SetFontFamily("宋体", FontCharRange.None);//设置雅黑字体

                if (act != null)
                {
                    act.Invoke(str, p1, runTitle);
                }
            });

        }

        public  void BuliderWorldAsync(string docPath, string Name)
        {

                SetPageBottonNumber().Wait();
                if (!Directory.Exists(docPath)) { Directory.CreateDirectory(docPath); }
                string fileName = string.Format("{0}.docx", HttpUtility.UrlEncode(Name, System.Text.Encoding.UTF8));
                FileStream out1 = new FileStream(Path.Combine(docPath, fileName), FileMode.Create, FileAccess.Write);
                doc.Write(out1);
                out1.Close();
                out1.Dispose();

        }


        public async Task SetStylesDoc()
        {
            await Task.Run(() =>
            {
                XWPFStyles newStyles = doc.CreateStyles();
                string filename =_config["StylePath"];
                XWPFDocument template = new XWPFDocument(new FileStream(filename, FileMode.Open, FileAccess.Read));
                var style = template.GetCTStyle();
                newStyles.SetStyles(style);
            });

        }

        public void  CreateTable()
        {
                var tableTop = doc.CreateTable(4, 2);
                tableTop.Width = 1000 * 3;
                tableTop.SetColumnWidth(0, 800); /* 设置列宽 */
                tableTop.SetColumnWidth(0, 2200); /* 设置列宽 */
                tableTop.GetRow(0).GetCell(0).SetParagraph(SetCellText(doc, tableTop, "县（区）"));
                tableTop.GetRow(0).GetCell(1).SetParagraph(SetCellText(doc, tableTop, "污水厂"));

                for (var i = 1; i < 4; i++)
                {
                    tableTop.GetRow(i)
                        .GetCell(0)
                        .SetParagraph(SetCellText(doc, tableTop, "******"));
                    tableTop.GetRow(i)
                        .GetCell(1)
                        .SetParagraph(SetCellText(doc, tableTop, "**********************"));
                }
        }
        public void CreateTable(int row = 4, int col = 2, Action<XWPFTable, XWPFDocument> action = null)
        {
            
                var tableTop = doc.CreateTable(row, col);

                if (action != null)
                {
                    action.Invoke(tableTop, doc);
                }
                else
                {
                    tableTop.Width = 1000 * 3;
                    tableTop.SetColumnWidth(0, 800); /* 设置列宽 */
                    tableTop.SetColumnWidth(0, 2200); /* 设置列宽 */
                    tableTop.GetRow(0).GetCell(0).SetParagraph(SetCellText(doc, tableTop, "县（区）"));
                    tableTop.GetRow(0).GetCell(1).SetParagraph(SetCellText(doc, tableTop, "污水厂"));
                    for (var i = 1; i < row; i++)
                    {
                        tableTop.GetRow(i)
                            .GetCell(0)
                            .SetParagraph(SetCellText(doc, tableTop, "******"));
                        tableTop.GetRow(i)
                            .GetCell(1)
                            .SetParagraph(SetCellText(doc, tableTop, "**********************"));
                    }
                }

                                                                                                                                                                                                                  }
        public XWPFParagraph SetCellText(XWPFDocument doc, XWPFTable table, string setText,int size=12)
        {
            //table中的文字格式设置  
            CT_P para = new CT_P();
            XWPFParagraph pCell = new XWPFParagraph(para, table.Body);
            pCell.Alignment = ParagraphAlignment.CENTER;//字体居中  
            pCell.VerticalAlignment = TextAlignment.CENTER;//字体居中  

            XWPFRun r1c1 = pCell.CreateRun();
            r1c1.SetText(setText);
            r1c1.FontSize = size;
            r1c1.SetFontFamily("华文楷体", FontCharRange.None);//设置雅黑字体  
            return pCell;
        }

        public XWPFParagraph SetCellText(XWPFDocument doc, XWPFTable table, string setText,
            ParagraphAlignment align, int textPos,int size=12)
        {
            CT_P para = new CT_P();
            XWPFParagraph pCell = new XWPFParagraph(para, table.Body);
            //pCell.Alignment = ParagraphAlignment.LEFT;//字体  
            pCell.Alignment = align;

            XWPFRun r1c1 = pCell.CreateRun();
            r1c1.SetText(setText);
            r1c1.FontSize =size;
            r1c1.SetFontFamily("华文楷体", FontCharRange.None);//设置雅黑字体  
            //r1c1.SetTextPosition(textPos);//设置高度  

            return pCell;
        }

        public void AddPic(string path, int width, int height)
        {
            if (!File.Exists(path))
            {
                return;
            }
            PicIndex++;
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            var id = doc.AddPictureData(fs, (int)PictureType.PNG);
            int EMU = 9525;
            width *= EMU;
            height *= EMU;

            string picXml = ""
                    //+ "<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">"
                    //+ "   <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"
                    + "      <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\" xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">"
                    + "         <pic:nvPicPr>" + "            <pic:cNvPr id=\""
                    + "0"
                    + "\" name=\"Generated\"/>"
                    + "            <pic:cNvPicPr/>"
                    + "         </pic:nvPicPr>"
                    + "         <pic:blipFill>"
                    + "            <a:blip r:embed=\""
                    + id
                    + "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>"
                    + "            <a:stretch>"
                    + "               <a:fillRect/>"
                    + "            </a:stretch>"
                    + "         </pic:blipFill>"
                    + "         <pic:spPr>"
                    + "            <a:xfrm>"
                    + "               <a:off x=\"0\" y=\"0\"/>"
                    + "               <a:ext cx=\""
                    + width
                    + "\" cy=\""
                    + height
                    + "\"/>"
                    + "            </a:xfrm>"
                    + "            <a:prstGeom prst=\"rect\">"
                    + "               <a:avLst/>"
                    + "            </a:prstGeom>"
                    + "         </pic:spPr>"
                    + "      </pic:pic>";
            //+ "   </a:graphicData>" + "</a:graphic>";
            var run = doc.CreateParagraph().CreateRun();
            CT_Inline inline = run.GetCTR().AddNewDrawing().AddNewInline();

            inline.graphic = new CT_GraphicalObject();
            inline.graphic.graphicData = new CT_GraphicalObjectData();
            inline.graphic.graphicData.uri = "http://schemas.openxmlformats.org/drawingml/2006/picture";

            // CT_GraphicalObjectData graphicData = inline.graphic.AddNewGraphicData();
            // graphicData.uri = "http://schemas.openxmlformats.org/drawingml/2006/picture";

            //XmlDocument xmlDoc = new XmlDocument();
            try
            {
                //xmlDoc.LoadXml(picXml);
                //var element = xmlDoc.DocumentElement;
                inline.graphic.graphicData.AddPicElement(picXml);

            }
            catch (XmlException)
            {

            }
            var extent = inline.AddNewExtent();
            extent.cx = width;
            extent.cy = height;
            var docPr = inline.AddNewDocPr();
            docPr.id = 1;
            docPr.name = "Image" + id;
            fs.Close();
            fs.Dispose();
        }
        public void  SavePicture(string id, int width, int height)
        {
          
                int EMU = 9525;
                width *= EMU;
                height *= EMU;

                string picXml = ""
                        //+ "<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">"
                        //+ "   <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"
                        + "      <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\" xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">"
                        + "         <pic:nvPicPr>" + "            <pic:cNvPr id=\""
                        + "0"
                        + "\" name=\"Generated\"/>"
                        + "            <pic:cNvPicPr/>"
                        + "         </pic:nvPicPr>"
                        + "         <pic:blipFill>"
                        + "            <a:blip r:embed=\""
                        + id
                        + "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>"
                        + "            <a:stretch>"
                        + "               <a:fillRect/>"
                        + "            </a:stretch>"
                        + "         </pic:blipFill>"
                        + "         <pic:spPr>"
                        + "            <a:xfrm>"
                        + "               <a:off x=\"0\" y=\"0\"/>"
                        + "               <a:ext cx=\""
                        + width
                        + "\" cy=\""
                        + height
                        + "\"/>"
                        + "            </a:xfrm>"
                        + "            <a:prstGeom prst=\"rect\">"
                        + "               <a:avLst/>"
                        + "            </a:prstGeom>"
                        + "         </pic:spPr>"
                        + "      </pic:pic>";
                //+ "   </a:graphicData>" + "</a:graphic>";
                var run = doc.CreateParagraph().CreateRun();
                CT_Inline inline = run.GetCTR().AddNewDrawing().AddNewInline();

                inline.graphic = new CT_GraphicalObject();
                inline.graphic.graphicData = new CT_GraphicalObjectData();
                inline.graphic.graphicData.uri = "http://schemas.openxmlformats.org/drawingml/2006/picture";

                // CT_GraphicalObjectData graphicData = inline.graphic.AddNewGraphicData();
                // graphicData.uri = "http://schemas.openxmlformats.org/drawingml/2006/picture";

                //XmlDocument xmlDoc = new XmlDocument();
                try
                {
                    //xmlDoc.LoadXml(picXml);
                    //var element = xmlDoc.DocumentElement;
                    inline.graphic.graphicData.AddPicElement(picXml);

                }
                catch (XmlException)
                {

                }
                var extent = inline.AddNewExtent();
                extent.cx = width;
                extent.cy = height;
                var docPr = inline.AddNewDocPr();
                docPr.id = 1;
                docPr.name = "Image" + id;
        }

        public async Task SetPageBottonNumber()
        {

            await Task.Run(() => {   
            CT_Ftr m_ftr = new CT_Ftr();

            m_ftr.Items = new System.Collections.ArrayList();

            CT_SdtBlock m_Sdt = new CT_SdtBlock();
            doc.Document.body.sectPr=new CT_SectPr();
             CT_SectPr m_SectPr = doc.Document.body.sectPr;

            CT_SdtPr m_SdtPr = m_Sdt.AddNewSdtPr();

            CT_SdtDocPart m_SdtDocPartObj = m_SdtPr.AddNewDocPartObj();

            m_SdtDocPartObj.AddNewDocPartGallery().val = "PageNumbers (Bottom of Page)";

            m_SdtDocPartObj.docPartUnique = new CT_OnOff();



            CT_SdtContentBlock m_SdtContent = m_Sdt.AddNewSdtContent();

            CT_P m_SdtContentP = m_SdtContent.AddNewP();

            CT_PPr m_SdtContentPpPr = m_SdtContentP.AddNewPPr();

            m_SdtContentPpPr.AddNewJc().val = ST_Jc.center;

            m_SdtContentP.Items = new System.Collections.ArrayList();

            CT_SimpleField m_fldSimple = new CT_SimpleField();

            m_fldSimple.instr = " PAGE   \\*MERGEFORMAT ";



            m_SdtContentP.Items.Add(m_fldSimple);

            m_ftr.Items.Add(m_Sdt);



            //创建页脚关系（footern.xml）

            XWPFRelation Frelation = XWPFRelation.FOOTER;

            XWPFFooter m_f = (XWPFFooter)doc.CreateRelationship(Frelation, XWPFFactory.GetInstance(), doc.FooterList.Count + 1);

            //设置页脚

            m_f.SetHeaderFooter(m_ftr);

            CT_HdrFtrRef m_HdrFtr = m_SectPr.AddNewFooterReference();

            m_HdrFtr.type = ST_HdrFtr.@default;

            m_HdrFtr.id = m_f.GetPackageRelationship().Id;});
        }
    }
}
